/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/4/24 12:20
 */
package org.mechanic.fund.service.product.impl;

import org.mechanic.core.Constants;
import org.mechanic.fund.domain.product.ProductType;
import org.mechanic.fund.domain.utils.mapper.DtoBeanMapper;
import org.mechanic.fund.repository.product.ProductTypeRepository;
import org.mechanic.fund.service.product.IProductTypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 产品系列服务实现
 *
 * @author mechanic
 * @version 0.0.1
 */
@Service
public class ProductTypeService implements IProductTypeService {

    private static Logger logger = LoggerFactory.getLogger(ProductTypeService.class);


    private ProductTypeRepository productTypeRepository;

    @Autowired
    public ProductTypeService(ProductTypeRepository productTypeRepository) {
        this.productTypeRepository = productTypeRepository;
    }
    /**
     * 返回按sort字段升序排序的产品系列列表
     * @return 产品系列列表
     */
    @Override
    @Cacheable(value = Constants.EHCACHE_NAME)
    public List<ProductType> getProductTypeList(){
        Order order = new Order(Direction.ASC, "sort");
        Sort sort = new Sort(order);
        return (List<ProductType>)this.productTypeRepository.findAll(sort);
    }

    /**
     * 返回匹配指定主键编号的对象
     *
     * @param id 主键编号
     * @return 对象实体
     */
    @Override
    @Cacheable(value = Constants.EHCACHE_NAME)
    public ProductType getById(String id) {
        return this.productTypeRepository.findOne(id);
    }

    /**
     * 保存。 主键为空则create，不为空则update。
     * @param productTypes 被保存的对象
     */
    @Override
    public void save(List<ProductType> productTypes, String operationUserId) {
        this.productTypeRepository.save(DtoBeanMapper.setOperationToList(productTypes, operationUserId));
    }
    /**
     * 删除匹配主键ID的对象
     * @param id 主键ID
     */
    @Override
    public void delete(String id) {
        try {
            this.productTypeRepository.delete(id);
        } catch (EmptyResultDataAccessException e) {
            logger.info(id + "不存在");
        }
    }
}
